package com.smssalama.gui;

import java.util.Date;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;

import com.smssalama.AlertManager;
import com.smssalama.SMSSalama;
import com.smssalama.SMSSalamaSession;
import com.smssalama.i18n.CommandLabels;
import com.smssalama.i18n.Labels;
import com.smssalama.storage.sms.SMSMessage;
import com.smssalama.storage.sms.SMSMessageIn;
import com.smssalama.storage.sms.SMSMessageOut;

public class SMSMessageViewer extends javax.microedition.lcdui.Form implements
		CommandListener {
	private Labels LABELS = Labels.labels();
	private CommandLabels CMD_LABELS = CommandLabels.cmdLabels();

	StringItem phoneNumber = new StringItem(LABELS.from() + "\n", "");
	StringItem timestamp = new StringItem(LABELS.date() + "\n", "");
	StringItem messageText = new StringItem(LABELS.message() + "\n", "");
	TextField password = new TextField(LABELS.password() + "\n", "",
			100, TextField.PASSWORD);

	Command deleteCmd = new Command(CMD_LABELS.delete(),
			Command.ITEM, 2);
	Command replyCmd = new Command("Reply", Command.ITEM, 2);
	Command decryptCmd = new Command("Decrypt", Command.ITEM, 1);

	SMSMessage message;

	public SMSMessageViewer(SMSMessage message) {
		super(SMSSalamaSession.getSession().getUserSettings()
				.getDisplayNameCache().getPhoneNumberDisplayName(
						message.getPhoneNumber()));
		setMessage(message);
	}

	private void setMessage(SMSMessage message) {
		this.message = message;
		this.deleteAll();
		this.phoneNumber.setPreferredSize(Integer.MAX_VALUE, -1);
		this.phoneNumber.setText(SMSSalamaSession.getSession()
				.getUserSettings().getDisplayNameCache()
				.getPhoneNumberDisplayName(message.getPhoneNumber()));
		this.append(this.phoneNumber);
		this.timestamp.setPreferredSize(Integer.MAX_VALUE, -1);
		this.timestamp.setText(new Date(message.getTimestamp()).toString());
		this.append(this.timestamp);

		this.removeCommand(this.decryptCmd);
		if (message instanceof SMSMessageIn) {
			SMSMessageIn messageIn = (SMSMessageIn) message;
			if (!messageIn.isEncrypted()) {
				this.messageText.setText(messageIn.getMessageText());
				this.messageText.setPreferredSize(Integer.MAX_VALUE, -1);
				this.append(this.messageText);
			} else {
				// messageText.setText(messageIn.getData());
				this.messageText.setPreferredSize(Integer.MAX_VALUE, -1);
				this.append(this.messageText);
				StringBuffer encrypted = new StringBuffer();
				for (int i = 0; i < messageIn.getData().length; i++) {
					encrypted = encrypted.append("*");
				}
				this.messageText.setText(encrypted.toString());
				this.append(this.password);
				this.addCommand(this.decryptCmd);
			}
		} else if (message instanceof SMSMessageOut) {
			SMSMessageOut messageOut = (SMSMessageOut) message;
			StringItem status = new StringItem(LABELS.status(),
					LABELS.messageOutStatus(messageOut.getStatus()) + "");
			status.setPreferredSize(Integer.MAX_VALUE, -1);
			this.append(status);
			this.messageText.setText(messageOut.getMessageText());
			this.messageText.setPreferredSize(Integer.MAX_VALUE, -1);
			this.append(this.messageText);
		}
		if (message instanceof SMSMessageIn
				&& !((SMSMessageIn) message).isEncrypted()) {
			this.addCommand(this.replyCmd);
		} else {
			this.removeCommand(this.replyCmd);
		}
		this.addCommand(this.deleteCmd);
		// this.addCommand(new Command(CommandLabels.cmdLabels.back(),
		// Command.BACK, 1));
		// this.addCommand(new Command("Exit", Command.EXIT, 3));
		// this.addCommand(new Command("Send Message", Command.ITEM, 1));
	}

	public SMSMessageViewer(int messageId) throws Exception {
		this((SMSMessage) SMSSalamaSession.getSession().getUserSettings()
				.getMessagesStore().getStorable(messageId));
	}

	public void commandAction(Command command, Displayable displayable) {
		if (command.getCommandType() == Command.BACK) {

		} else if (command.getCommandType() == Command.EXIT) {
			SMSSalama.quitApp();
		}
		if (command == this.decryptCmd && this.message instanceof SMSMessageIn) {
			try {
				((SMSMessageIn) this.message).decrypt(this.password.getString());
				this.setMessage(this.message);
				SMSSalamaSession.getSession().getUserSettings()
						.getMessagesStore().persistStorable(this.message);
			} catch (Exception e) {
				e.printStackTrace();
				Alert alert = new Alert("SMS Salama Error",
						"Failed to open message using the given password.",
						null, AlertType.ERROR);
				alert.setCommandListener(new CommandListener() {
					public void commandAction(Command arg0, Displayable arg1) {
						SMSMessageViewer.this.password.setString("");
						//Display.getDisplay(SMSSalama.getInstance()).setCurrentItem(SMSMessageViewer.this.password);
						AlertManager.showItem(SMSMessageViewer.this.password);
					}
				});
				Display.getDisplay(SMSSalama.getInstance()).setCurrent(alert, this);
				// AlertManager.showError(displayable, e);
				// AlertManager.showError("Failed to open message using the
				// given password.");
			}
		}
	}
}
